package com.apes.fn.pi.inventory;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransfer;
import com.apes.fn.scm.crossCompany.transfer.repository.CrossCompanyTransferRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.repository.ContractRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrderItem;
import com.apes.scm.pur.purchaseOrder.service.PurchaseService;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName FnInterface
 * @Description TODO
 * @Author pengyb
 * @Date 2019/12/6 11:25
 * @Version 1.0
 **/
@Service("fnService")
public class FnService extends DomainService {

    @Autowired
    private PurchaseService purchaseService;

    /**
     * 寄售库存下发
     *
     * @param request
     * @return
     */
    public PurchaseOrder consignmentStockIssued(SimpleRequest request) {
        PurchaseOrder purchaseOrder = request.getO(PurchaseOrder.class);
        //供应商 默认集群车宝
        purchaseOrder.setSupplier(SpringManager.getBean(PartyRoleRepository.class).findOne("A1001"));
        purchaseOrder.setCompany(purchaseOrder.getLocation().getCompany());
        if (Objects.nonNull(purchaseOrder.getOrigin())) {
            CrossCompanyTransfer crossCompanyTransfer = SpringManager.getBean(CrossCompanyTransferRepository.class).findOne(purchaseOrder.getOrigin());
            if (crossCompanyTransfer != null) {
                purchaseOrder.setReceiptLocation(crossCompanyTransfer.getShipLocation());
            }
        }

        try {
            Contract contract = SpringManager.getBean(ContractRepository.class).findAll(
                    JpaDsl.toCriteriaByEq(
                            "cooperation.id", purchaseOrder.getCooperation().getId(),
                            "contractType.code", "supplier",
                            "partner.id", "A1001", "company.id",
                            purchaseOrder.getCompany().getId(), "state", "approve"
                    )
            ).stream().filter(c -> c.getValidPeriod().after(new Date())).findFirst().get();
            purchaseOrder.setContract(contract);
            purchaseOrder.setDept(contract.getDept());
            purchaseOrder.setClerk(contract.getPartner());
        } catch (Exception e) {
            throw new RuntimeException("采购合同异常，请检查公司(" + purchaseOrder.getCompany().getName() + ")下的采购合同");
        }
        Optional<Enumeration> enumeration = SpringManager.getBean(EnumerationRepository.class).findOne(JpaDsl.toCriteriaByEq("code", request.get("type")));
        purchaseOrder.setMoveType(enumeration.get());
        //默认标准采购
        purchaseOrder.setScene(SpringManager.getBean(SceneRepository.class).findOne("PO001"));
        request.setData(null);
        List<PurchaseOrderItem> purchaseItems = new ArrayList<>();
        purchaseOrder.getPurchaseItems().clear();
        request.getJO().getJSONArray("purchaseItems").forEach(purchaseItem -> {
            JSONObject item = (JSONObject) purchaseItem;
            PurchaseOrderItem orderItem = new PurchaseOrderItem();
            List<Product> products = SpringManager.getBean(ProductRepository.class).findAll(JpaDsl.toCriteriaByEq("orginID", item.getString("product")));
            if (products.isEmpty()) {
                throw new RuntimeException("无此商品");
            }
            if (products.size() > 1) {
                throw new RuntimeException("商品数据存在误差，无法根据来源商品id:" + item.getString("product") + " 获取对应的商品数据");
            }
            Tax tax = SpringManager.getBean(TaxRepository.class).findAll(JpaDsl.toCriteriaByEq("amt", (item.getDouble("tax") * 100))).stream().findFirst().get();
            orderItem.setProduct(products.stream().findFirst().get());
            List<ProductUom> productUoms = SpringManager.getBean(ProductUomRepository.class).findAll(JpaDsl.toCriteriaByEq("name", item.getString("uom"), "uomCategory.id", orderItem.getProduct().getId()));
            if (productUoms.size() == 0) {
                throw new RuntimeException("商品单位数据存在误差，该商品缺少[" + item.getString("uom") + " ]的计量单位数据");
            }
            orderItem.setPriceUnit(item.getDouble("priceUnit"));
            orderItem.setEffectiveQty(item.getDoubleValue("effectiveQty"));
            orderItem.setProductUomQty(item.getDouble("productUomQty"));
            orderItem.setName(item.getString("name"));
            orderItem.setUom(productUoms.stream().findFirst().get());
            orderItem.setTax(tax);
            orderItem.setPurchaseOrder(purchaseOrder);
            orderItem.computeAmt();
            purchaseItems.add(orderItem);
        });
        purchaseOrder.setPurchaseItems(purchaseItems);
        //生成采购单
        List<User> userInfo = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", purchaseOrder.getCreator()));
        if (userInfo.size() != 0) purchaseOrder.setUserId(userInfo.get(0).getId().toString());
        PurchaseOrder saveOrder = purchaseService.save(purchaseOrder);

        //审批
        if (purchaseOrder.getApproveUid() == null) {
            throw new RuntimeException("审核人为空！");
        }
        PurchaseOrder order = this.invoke("purchase.order.approve", MapUtil.mapped(saveOrder));
        return order;
    }


}
